import { writeFile, utils, read } from "xlsx";
import { saveAs } from "file-saver";

/**
 * 导出表格 简单导出
 * @param {*} filename 
 * @param {*} data 
 */
export function exportXlsx(filename, data) {
    const ws = utils.json_to_sheet(data);
    // 新建book
    const wb = utils.book_new();
    // 生成xlsx文件(book,sheet数据,sheet命名)
    utils.book_append_sheet(wb, ws, "工作蒲1");
    // const sheet = wb.Sheets[wb.SheetNames[0]];
    // let dw = ['选项 1', '选项 2', '选项 3'];
    let blob = writeFile(wb, `${filename}.xlsx`);
    saveAs(blob, `${filename}.xlsx`);
}

/**
 * 读取文件
 */
export function readXlsx(file, sheet = '工作蒲1', fn = () => { }) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
            const { result } = e.target
            try {
                const workbook = read(result, { type: 'binary' })
                console.log(workbook)
                const json_data = utils.sheet_to_json(workbook.Sheets[sheet]);
                let data = json_data.map((item) => {
                    return fn(item)
                })
                resolve(data);

            } catch (error) {
                console.error(error)
                reject(error);
            }

        }
        reader.onerror = (error) => {
            console.error(error)
            reject(error);
        }
        reader.readAsArrayBuffer(file)
    })

}